import { Text, useMessage } from 'alemonjs'
import { selects, validate } from '@src/apps/index'
import {
  sequelize,
  user,
  main_story,
  race_base,
  user_attribute,
  race_extra
} from '@src/db'
import {
  qidToUid,
  updateUserAttributes,
  battleInitialization,
  loadPlayerAttributes,
  loadEnemyAttributes
} from '@src/apps/tools'

export const regular = /^(!|！|\/)?选择/

const response = onResponse(selects, async e => {
  const [message] = useMessage(e)
  const userId = await qidToUid(e.UserId ?? e.UserKey)

  // 获取用户信息
  const userInfo = await user.findOneValue({ where: { uid: userId } })

  // 获取当前进度
  const schedule = String(userInfo.schedule || '')
  if (!schedule) {
    message.send(format(Text('\n你不在剧情中！')))
    return
  }

  // 获取当前剧情 story_id
  const storyInfo = await main_story.findOneValue({
    where: { story_id: schedule }
  })
  if (!storyInfo) {
    message.send(format(Text('\n剧情节点不存在，请联系管理员！')))
    return
  }

  // 匹配指令选择的数字
  const match = /^(!|！|\/)?选择\s*(\d+)$/.exec(e.MessageText || '')
  const selectNum = match && match[2] ? Number(match[2]) : 0

  if (
    !storyInfo.options ||
    !Array.isArray(storyInfo.options) ||
    selectNum < 1 ||
    selectNum > storyInfo.options.length
  ) {
    message.send(format(Text('\n选项无效，请重新选择！')))
    return
  }

  // 获取选中的 option
  const selectedOption = storyInfo.options[selectNum - 1]
  const nextId = String(selectedOption.next_id)

  // 查询下一个剧情
  const nextStory = await main_story.findOneValue({
    where: { story_id: nextId }
  })
  if (!nextStory) {
    message.send(format(Text('\n后续剧情缺失，请联系管理员！')))
    return
  }

  // 处理 schedule
  let newSchedule = ''
  const allNumber = storyInfo.options.every(opt =>
    /^[0-9]+$/.test(String(opt.next_id))
  )
  if (allNumber) {
    // 全为数字，schedule 追加
    newSchedule = `${schedule}${nextId}`
  } else {
    // 有汉字，schedule 直接替换为用户选择的 next_id
    newSchedule = nextId
  }

  // 更新用户进度
  await user.update({ schedule: newSchedule }, { where: { uid: userId } })

  let q1 = ''
  let q2 = ''
  let q3 = ''
  // 判定things
  if (
    nextStory.things &&
    Array.isArray(nextStory.things) &&
    nextStory.things.length > 0
  ) {
    for (const thing of nextStory.things) {
      if (
        thing &&
        typeof thing === 'object' &&
        'type' in thing &&
        thing.type === '种族初始化'
      ) {
        // 读取种族属性
        const race = await race_base.findOneValue({
          where: { race_name: thing.value }
        })
        if (race) {
          // 写入user_attribute表
          await user_attribute.upsert({
            uid: userId,
            race: race.race_name,
            constitution_base: race.constitution_base ?? 0,
            spirit_base: race.spirit_base ?? 0,
            strength_base: race.strength_base ?? 0,
            intelligence_base: race.intelligence_base ?? 0,
            agility_base: race.agility_base ?? 0,
            perception_base: race.perception_base ?? 0,
            charm_base: race.charm_base ?? 0,
            luck_base: race.luck_base ?? 0,
            constitution_growth: race.constitution_growth ?? 0,
            spirit_growth: race.spirit_growth ?? 0,
            strength_growth: race.strength_growth ?? 0,
            intelligence_growth: race.intelligence_growth ?? 0,
            agility_growth: race.agility_growth ?? 0,
            perception_growth: race.perception_growth ?? 0,
            charm_growth: race.charm_growth ?? 0,
            luck_growth: race.luck_growth ?? 0
            // 如有其它属性可继续补充
          })
          await updateUserAttributes(userId)

          // 将user_attribute里该userId用户hp和mp初始化为hp_max和mp_max
          await user_attribute.update(
            {
              hp: sequelize.literal('hp_max'),
              mp: sequelize.literal('mp_max')
            },
            { where: { uid: userId } }
          )
        }
      } else if (
        thing !== null &&
        typeof thing === 'object' &&
        'type' in thing &&
        thing.type === '种族词条'
      ) {
        // 读取种族属性
        const aff = await race_extra.findOneValue({
          where: {
            race_name: thing?.value?.race_name,
            affixes: thing?.value?.affixes
          }
        })
        if (aff) {
          // 先查出原有属性
          const oldAttr: {
            constitution_base?: number
            spirit_base?: number
            strength_base?: number
            intelligence_base?: number
            agility_base?: number
            perception_base?: number
            charm_base?: number
            luck_base?: number
            constitution_growth?: number
            spirit_growth?: number
            strength_growth?: number
            intelligence_growth?: number
            agility_growth?: number
            perception_growth?: number
            charm_growth?: number
            luck_growth?: number
            // 如有其它属性可继续补充
          } =
            (await user_attribute.findOneValue({ where: { uid: userId } })) ||
            {}

          // 在原数值上加减
          await user_attribute.upsert({
            uid: userId,
            constitution_base:
              (oldAttr.constitution_base ?? 0) + (aff.constitution_base ?? 0),
            spirit_base: (oldAttr.spirit_base ?? 0) + (aff.spirit_base ?? 0),
            strength_base:
              (oldAttr.strength_base ?? 0) + (aff.strength_base ?? 0),
            intelligence_base:
              (oldAttr.intelligence_base ?? 0) + (aff.intelligence_base ?? 0),
            agility_base: (oldAttr.agility_base ?? 0) + (aff.agility_base ?? 0),
            perception_base:
              (oldAttr.perception_base ?? 0) + (aff.perception_base ?? 0),
            charm_base: (oldAttr.charm_base ?? 0) + (aff.charm_base ?? 0),
            luck_base: (oldAttr.luck_base ?? 0) + (aff.luck_base ?? 0),
            constitution_growth:
              (oldAttr.constitution_growth ?? 0) +
              (aff.constitution_growth ?? 0),
            spirit_growth:
              (oldAttr.spirit_growth ?? 0) + (aff.spirit_growth ?? 0),
            strength_growth:
              (oldAttr.strength_growth ?? 0) + (aff.strength_growth ?? 0),
            intelligence_growth:
              (oldAttr.intelligence_growth ?? 0) +
              (aff.intelligence_growth ?? 0),
            agility_growth:
              (oldAttr.agility_growth ?? 0) + (aff.agility_growth ?? 0),
            perception_growth:
              (oldAttr.perception_growth ?? 0) + (aff.perception_growth ?? 0),
            charm_growth: (oldAttr.charm_growth ?? 0) + (aff.charm_growth ?? 0),
            luck_growth: (oldAttr.luck_growth ?? 0) + (aff.luck_growth ?? 0)
            // 如有其它属性可继续补充
          })
          await updateUserAttributes(userId)
        }
      } else if (
        thing !== null &&
        typeof thing === 'object' &&
        'type' in thing &&
        thing.type === '进入战斗'
      ) {
        // 进入战斗
        // 异步另外发送一条消息，延时发送不影响后续程序进行
        q1 = '\n【进入战斗】\n'
        // 读取玩家属性
        const playerAttr = await loadPlayerAttributes(userId)
        // 读取敌人属性
        const enemyAttr = await loadEnemyAttributes(thing?.value)
        // 战斗初始化
        await battleInitialization(playerAttr, enemyAttr, '普通战斗')
        setTimeout(() => {
          message.send(
            format(Text('\n【战斗加载完成】\n发送[战斗面板]查看战斗详情'))
          )
        }, 1000)
      } else if (
        thing !== null &&
        typeof thing === 'object' &&
        'type' in thing &&
        thing.type === '位置切换'
      ) {
        // user表UserId位置字段更新
        const newLocation = thing.value || ''
        // 获取坐标，如果xy是未知或者没有取1-99随机数
        const coordinate_x = newLocation.x || ''
        const coordinate_y = newLocation.y || ''
        if (!coordinate_x) {
          // 如果没有坐标，随机生成1-99之间的数字
          newLocation.x = Math.floor(Math.random() * 99) + 1
        }
        if (!coordinate_y) {
          // 如果没有坐标，随机生成1-99之间的数字
          newLocation.y = Math.floor(Math.random() * 99) + 1
        }

        // 获取地名
        const map = newLocation.map || ''
        await user.update(
          { map, coordinate_x, coordinate_y },
          { where: { uid: userId } }
        )
      } else if (
        thing !== null &&
        typeof thing === 'object' &&
        'type' in thing &&
        thing.type === '文字提示'
      ) {
        // 发送文字提示
        setTimeout(() => {
          message.send(format(Text(`\n${thing.value}`)))
        }, 1000)
      }
      // 可扩展其它type判定
    }
  }

  // 发送剧情内容
  let content = `\n【${nextStory.title}】\n${nextStory.content}${q1}${q2}${q3}`
  if (
    nextStory.options &&
    Array.isArray(nextStory.options) &&
    nextStory.options.length > 0
  ) {
    content += '\n——————————————\n'
    content += nextStory.options
      .map((opt: any, idx: number) => `[${idx + 1}] ${opt.text}`)
      .join('\n')
    content += '\n——————————————\n发送[选择+数字]进行'
  }
  message.send(format(Text(content)))
})

export default onResponse(selects, [validate, response.current])
